package com.jerry.hm.datastructure.queue;

import java.util.Iterator;

/**
 * 环形数组实现-方式二
 *
 * @author Jerry
 * @since 2024/10/3 13:00
 */
public class ArrayQueue2<E> implements Queue<E>, Iterable<E> {

    private final E[] array;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public ArrayQueue2(int capacity) {
        array = (E[]) new Object[capacity];
    }

    /**
     * 向队尾插入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        array[tail] = e;
        tail = (tail + 1) % array.length;
        size++;
        return true;
    }

    /**
     * 从队首移除元素
     *
     * @return
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E target = array[head];
        array[head] = null;
        head = (head + 1) % array.length;
        size--;
        return target;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    /**
     * 队列是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 队列是否已满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return size == array.length;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            private int cur = head;
            private int count = 0;

            @Override
            public boolean hasNext() {
                return count < size;
            }

            @Override
            public E next() {
                E target = array[cur];
                cur = (cur + 1) % array.length;
                count++;
                return target;
            }
        };
    }
}
